import * as mars3d from "mars3d"
import axios from "axios"
import { useWidget } from "@mars/common/store/widget"

const Cesium = mars3d.Cesium
let map: mars3d.Map // 地图对象
export let station = null // 当前选中基础站点信息
export let stationName = null // 当前选中站点名称
export let NJstation = null // 当前选中农机站点信息
export let yjstation = null // 当前选中应急站点信息
let graphicLayer: mars3d.layer.GraphicLayer = null // 全局矢量图层引用

// 初始化地图业务
export function onMounted(mapInstance) {
  console.log("初始化")
  map = mapInstance
  const { activate, disable } = useWidget()

  // 初始化矢量图层并保存引用
  graphicLayer = new mars3d.layer.GraphicLayer({
    zIndex: 100
  })
  map.addLayer(graphicLayer)

  // 绑定图层点击事件
  graphicLayer.on(mars3d.EventType.click, async (event) => {
    console.log("图层点击事件触发")
    await handleStationClick(event, activate, disable)
  })

  // 初始化加载基础数据
  addShangshui(graphicLayer, map)
  addStationMarkers(graphicLayer)
  addYJZDStation(graphicLayer)
}

// 处理站点点击事件
async function handleStationClick(
  event: any,
  activate: (widgetId: string) => void,
  disable: (widgetId: string) => void
) {
  console.log("处理站点点击事件")
  const graphic = event.graphic
  if (!graphic) {
    console.log("未获取到点击的图形对象")
    return
  }

  const attr = graphic.attr
  if (attr && attr.remark === "站点") {
    // 处理基础站点点击
    closeDialogs(disable)
    station = {
      id: attr.id || "未知ID",
      name: attr.name || "未知站点",
      longitude: graphic.position.lng,
      latitude: graphic.position.lat,
      hasTownship: attr.hasXzzmc || false,
      townshipName: attr.hasXzzmc && attr.xzzmc ? attr.xzzmc : "无乡镇信息"
    }

    try {
      await getStationById()
      console.log("当前选中基础站点:", station)
      openDialogs(activate)
    } catch (error) {
      console.error("处理基础站点信息时出错:", error)
    }
  } else if (attr && attr.remark === "农机专业合作社") {
    // 处理农机站点点击
    closeDialogs(disable)
    console.log("农机站点属性:", attr)

    NJstation = {
      id: attr.id || "未知ID",
      name: attr.name || "未知站点",
      longitude: graphic.position.lng,
      latitude: graphic.position.lat,
      hasTownship: attr.hasXzzmc || false,
      townshipName: attr.hasXzzmc && attr.xzzmc ? attr.xzzmc : "无乡镇信息"
    }

    try {
      await getNJStationById()
      console.log("当前选中农机站点:", NJstation)
      openDialogs(activate)
    } catch (error) {
      console.error("处理农机站点信息时出错:", error)
    }
  }
}

// 关闭所有对话框
function closeDialogs(disable: (widgetId: string) => void) {
  const dialogs = ["dialog1", "dialog2", "dialog3", "dialog5", "dialog6"]
  dialogs.forEach(dialogId => {
    try {
      disable(dialogId)
      console.log(`已关闭对话框: ${dialogId}`)
    } catch (error) {
      console.error(`关闭对话框 ${dialogId} 失败:`, error)
    }
  })
  // 重置站点数据
  station = null
  stationName = null
  NJstation = null
  yjstation = null
}

// 打开对应对话框
function openDialogs(enable: (widgetId: string) => void) {
  const dialogs1 = ["dialog1"]
  const dialogs2 = ["dialog2", "dialog3"]
  const dialogs3 = ["dialog5"]
  const dialogs4 = ["dialog6"]

  const openDialogsArray = (dialogArray: string[]) => {
    dialogArray.forEach(dialogId => {
      try {
        enable(dialogId)
        console.log(`已打开对话框: ${dialogId}`)
      } catch (error) {
        console.error(`打开对话框 ${dialogId} 失败:`, error)
      }
    })
  }

  // 根据不同站点类型打开对应对话框
  if (station) {
    console.log("基础站点不为空，打开 dialogs1 和 dialogs2")
    openDialogsArray(dialogs1)
    openDialogsArray(dialogs2)
  }
  if (NJstation) {
    console.log("农机站点不为空，打开 dialogs2 和 dialogs3")
    openDialogsArray(dialogs2)
    openDialogsArray(dialogs3)
  }
  if (yjstation) {
    console.log("应急站点不为空，打开 dialogs2、dialogs3 和 dialogs4")
    openDialogsArray(dialogs2)
    openDialogsArray(dialogs3)
    openDialogsArray(dialogs4)
  }
}

// 添加商水县地理信息
export function addShangshui(graphicLayer: mars3d.layer.GraphicLayer, map: mars3d.Map) {
  const shangshuiBounds = [114.38, 33.48, 114.72, 33.72]

  // 添加商水县卫星图
  const shangshuiImg = new mars3d.graphic.RectanglePrimitive({
    positions: [
      [shangshuiBounds[0], shangshuiBounds[1]],
      [shangshuiBounds[2], shangshuiBounds[3]]
    ],
    style: {
      height: 100,
      materialType: mars3d.MaterialType.Image2,
      materialOptions: {
        image: "https://maptiles.mars3d.cn/GoogleSatellite/default.jpg"
      },
      interactive: false
    }
  })
  graphicLayer.addGraphic(shangshuiImg)

  // 添加商水县边界墙
  const shangshuiWall = new mars3d.layer.GeoJsonLayer({
    name: "商水县边界墙",
    url: `${process.env.BASE_URL}geojson/shangshui_county.json`,
    symbol: {
      type: "wallP",
      styleOptions: {
        diffHeight: 1000,
        materialType: mars3d.MaterialType.Image2,
        materialOptions: {
          image: "https://data.mars3d.cn/img/textures/wall.png"
        }
      }
    }
  })
  map.addLayer(shangshuiWall)

  // 添加商水县详细边界标注
  const detailLayer = new mars3d.layer.GeoJsonLayer({
    name: "商水县详细边界",
    url: `${process.env.BASE_URL}geojson/411623.json`,
    symbol: {
      type: "polyline",
      styleOptions: {
        color: "rgba(255,255,255,0.3)",
        setHeight: 1000,
        width: 2,
        label: {
          text: "{name}",
          position: "center",
          font_size: 20,
          color: "black",
          font_family: "微软雅黑",
          outline: true,
          outlineColor: "#f1f3f4",
          outlineWidth: 2,
          scaleByDistance: true,
          scaleByDistance_far: 500000,
          scaleByDistance_farValue: 0.5,
          scaleByDistance_near: 10000,
          scaleByDistance_nearValue: 1
        },
        popup: "{name}"
      }
    }
  })
  map.addLayer(detailLayer)

  // 定位到商水县中心
  const centerLon = (shangshuiBounds[0] + shangshuiBounds[2]) / 2
  const centerLat = (shangshuiBounds[1] + shangshuiBounds[3]) / 2
  map.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, 50000)
  })
}

// 基础站点详情查询
export async function getStationById() {
  if (!station || !station.id) {
    throw new Error("基础站点ID不存在")
  }

  try {
    const { data } = await axios.get(`/api/system/quyuzhan/${station.id}`)
    console.log("基础站点详情响应:", data)

    if (data && data.code === 200) {
      station = { ...station, ...data.data }
      stationName = data.data.qyzmc
    } else {
      throw new Error(data.message || "获取基础站点详情失败")
    }
  } catch (error) {
    console.error("基础站点详情请求错误:", error)
    throw error
  }
}

// 农机站点详情查询
export async function getNJStationById() {
  if (!NJstation || !NJstation.id) {
    throw new Error("农机站点ID不存在")
  }

  try {
    const { data } = await axios.get(`/api/system/yingjifuwu/${NJstation.id}`)
    console.log("农机站点详情响应:", data)

    if (data && data.code === 200) {
      // 提取应急服务队信息
      if (data.data?.yjzyfwd) {
        yjstation = data.data.yjzyfwd
        console.log("成功获取应急服务队数据")
      } else {
        console.log("无应急服务队数据")
        yjstation = null
      }

      NJstation = { ...NJstation, ...data.data }
      stationName = data.data.yjdwmc
    } else {
      throw new Error(data.message || "获取农机站点详情失败")
    }
  } catch (error) {
    console.error("农机站点详情请求错误:", error)
    throw error
  }
}

// 添加基础站点标记
export async function addStationMarkers(graphicLayer: mars3d.layer.GraphicLayer) {
  try {
    const { data } = await axios.get("/api/system/quyuzhan/list?pageSize=50")
    console.log("基础站点列表响应:", data)

    if (data && data.code === 200) {
      const stations = data.rows || []
      console.log(`获取到${stations.length}个基础站点`)

      stations.forEach((stationData, index) => {
        if (stationData.lnt && stationData.lat) {
          const markerImage = stationData.xzzmc
            ? "https://data.mars3d.cn/img/marker/mark-blue.png"
            : "https://data.mars3d.cn/img/marker/mark-blue.png"

          const graphic = new mars3d.graphic.BillboardEntity({
            position: new mars3d.LngLatPoint(stationData.lnt, stationData.lat, 1000),
            style: {
              image: markerImage,
              scale: 1.5,
              horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              clickable: true,
              cursor: "pointer",
              heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
            },
            attr: {
              ...stationData,
              remark: "站点",
              hasXzzmc: !!stationData.xzzmc,
              index: index + 1
            }
          })

          // 绑定弹窗信息
          graphic.bindPopup(`
            <div class="mars-info-window">
              <div class="info-title">${stationData.qyzmc || "站点信息"}</div>
              <div class="info-content">
                <p>编号: ${stationData.number || "未提供"}</p>
                <p>${stationData.xzzmc ? `乡镇: ${stationData.xzzmc}` : "无乡镇信息"}</p>

                <p>技术职称: ${stationData.jszc || "未指定"}</p>
              </div>
            </div>
          `)

          graphicLayer.addGraphic(graphic)
        }
      })

      console.log(`成功添加${stations.length}个基础站点标记`)
    } else {
      console.error("获取基础站点列表失败:", data.message || "未知错误")
    }
  } catch (error) {
    console.error("添加基础站点标记错误:", error)
  }
}

// 添加应急站点标记
export async function addYJZDStation(graphicLayer: mars3d.layer.GraphicLayer) {
  try {
    const { data } = await axios.get("/api/system/yingjifuwu/list?pageSize=50")
    console.log("应急站点列表响应:", data)

    if (data && data.code === 200) {
      const stations = data.rows || []
      console.log(`获取到${stations.length}个应急站点`)

      // 图标定义
      const linkIcon = "https://data.mars3d.cn/img/marker/mark-red.png"
      const linkIcon1 = "https://data.mars3d.cn/img/marker/point-yellow.png"
      const linkIcon2 = "https://data.mars3d.cn/img/marker/lace-red.png"

      stations.forEach((stationData, index) => {
        if (stationData.lnt && stationData.lat) {
          // 图标选择逻辑
          let currentIcon = linkIcon2
          if (stationData.lyfwzx === "1") {
            currentIcon = linkIcon
          } else if (stationData.njyjfwd === "1") {
            currentIcon = linkIcon1
          }

          const graphic = new mars3d.graphic.BillboardEntity({
            position: new mars3d.LngLatPoint(stationData.lat, stationData.lnt, 1000),
            style: {
              image: currentIcon,
              scale: 1.8,
              horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              clickable: true,
              cursor: "pointer",
              heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
            },
            attr: {
              ...stationData,
              remark: "农机专业合作社",
              hasXzzmc: !!stationData.xzzmc,
              index: index + 1
            }
          })

          // 绑定弹窗信息
          graphic.bindPopup(`
            <div class="mars-info-window">
              <div class="info-title">${stationData.qyzmc || "站点信息"}</div>
              <div class="info-content">
                <p>合作社信息: ${stationData.yjdwmc || "未提供"}</p>

                <p>服务乡镇: ${stationData.fwxz || "未指定"}</p>
              </div>
            </div>
          `)

          // 点击事件：打开坐标链接
          graphic.on(mars3d.EventType.click, () => {
            if (stationData.coordinateLink) {
              window.open(stationData.coordinateLink, "_blank")
            }
          })

          graphicLayer.addGraphic(graphic)
        }
      })

      console.log(`成功添加${stations.length}个应急站点标记`)
    } else {
      console.error("获取应急站点列表失败:", data.message || "未知错误")
    }
  } catch (error) {
    console.error("添加应急站点标记错误:", error)
  }
}

// 新增：清除所有标记点
export function clearAllMarkers() {
  if (graphicLayer) {
    graphicLayer.clear()
    console.log("已清除所有标记点")
  } else {
    console.warn("图层未初始化，无法清除标记")
  }
}
// 新增：显示所有标记点

export async function showAllMarkers() {
  clearAllMarkers()
  await addStationMarkers(graphicLayer)
  await addYJZDStation(graphicLayer)
}
// 新增：只显示基础站点
export async function showOnlyQuyuzhanStations() {
  clearAllMarkers()
  await addStationMarkers(graphicLayer)
}

// 新增：只显示应急站点中lyfwzx=1的标记
export async function showOnlyYingjifuwuLyfwzx() {
  if (!graphicLayer) {
    return
  }

  try {
    const { data } = await axios.get("/api/system/yingjifuwu/list?pageSize=50")
    if (data?.code === 200) {
      clearAllMarkers()
      const filtered = (data.rows || []).filter(s => s.lyfwzx === "1")
      renderYingjifuwuMarkers(filtered, "https://data.mars3d.cn/img/marker/mark-red.png")
    }
  } catch (error) {
    console.error("筛选lyfwzx=1站点错误:", error)
  }
}

// 新增：只显示应急站点中njyjfwd=1的标记
export async function showOnlyYingjifuwuNjyjfwd() {
  if (!graphicLayer) {
    return
  }

  try {
    const { data } = await axios.get("/api/system/yingjifuwu/list?pageSize=50")
    if (data?.code === 200) {
      clearAllMarkers()
      const filtered = (data.rows || []).filter(s => s.njyjfwd === "1")
      renderYingjifuwuMarkers(filtered, "https://data.mars3d.cn/img/marker/point-yellow.png")
    }
  } catch (error) {
    console.error("筛选njyjfwd=1站点错误:", error)
  }
}

// 新增：只显示其他类型应急站点
export async function showOnlyYingjifuwuOther() {
  if (!graphicLayer) {
    return
  }

  try {
    const { data } = await axios.get("/api/system/yingjifuwu/list?pageSize=50")
    if (data?.code === 200) {
      clearAllMarkers()
      const filtered = (data.rows || []).filter(
        s => s.njyjfwd !== "1" && s.lyfwzx !== "1"
      )
      renderYingjifuwuMarkers(filtered, "https://data.mars3d.cn/img/marker/lace-red.png")
    }
  } catch (error) {
    console.error("筛选其他应急站点错误:", error)
  }
}

// 渲染应急站点标记的辅助函数
function renderYingjifuwuMarkers(stations: any[], icon: string) {
  stations.forEach((stationData, index) => {
    if (stationData.lnt && stationData.lat) {
      const graphic = new mars3d.graphic.BillboardEntity({
        position: new mars3d.LngLatPoint(stationData.lat, stationData.lnt, 1000),
        style: { image: icon, scale: 1.8 },
        attr: { ...stationData, remark: "农机专业合作社", index: index + 1 }
      })

      // 绑定弹窗（复用原有格式）
      graphic.bindPopup(`
        <div class="mars-info-window">
          <div class="info-title">${stationData.qyzmc || "站点信息"}</div>
          <div class="info-content">
            <p>合作社信息: ${stationData.yjdwmc || "未提供"}</p>

            <p>服务乡镇: ${stationData.fwxz || "未指定"}</p>
          </div>
        </div>
      `)

      graphicLayer.addGraphic(graphic)
    }
  })
  console.log(`已渲染${stations.length}个筛选站点标记`)
}

// 释放资源
export function onUnmounted() {
  map = null
  station = null
  stationName = null
  NJstation = null
  yjstation = null
  if (graphicLayer) {
    map?.removeLayer(graphicLayer)
    graphicLayer = null
  }
}
